<template>
  <div class="main goods-detail">
    <div class="btn-box">
      <h3>商品查看</h3>
      <div>
        <el-button class="filter-item" v-if="isEdit" type="success" size="small" @click="save">保存</el-button>
        <el-button class="filter-item" v-else @click="updateUpshelf" type="danger" size="small">下架</el-button>
      </div>
    </div>
    <section>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基础信息" name="base">
          <el-form :model="formData" ref="baseForm" label-width="120px"   :disabled="!isEdit">
            <el-form-item label="商品款号:" prop="serialNo">
              <span>{{formData.serialNo}}</span>
            </el-form-item>
            <el-form-item label="ERP商品名称:" prop="erpGoodsName">
              <span>{{formData.erpGoodsName}}</span>
            </el-form-item>
            <el-form-item label="后台分类:" prop="goodsName">
              <span>{{formData.backCatName}}</span>
            </el-form-item>
            <el-form-item label="商品名称:" :rules="commonRules.notNullRule" prop="name">
              <el-input placeholder="请输入商品名称" v-model="formData.name" />
            </el-form-item>
            <el-form-item label="商品副标题:" :rules="commonRules.notNullRule" prop="subName">
              <el-input placeholder="请输入商品副标题" v-model="formData.subName" />
            </el-form-item>
            <el-form-item label="经营模式:" :rules="commonRules.notNullRule" prop="businessModel">
              <el-select v-model="formData.businessModel" placeholder="请选择">
                <el-option label="招商" :value="2"></el-option>
                <el-option label="自营" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="品牌:" prop="brandId">
              <el-select v-model="formData.brandId" filterable placeholder="请选择">
                <el-option v-for="it in brands" :key="it.id" :label="it.name" :value="it.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="供应商:" prop="storehouseId" :rules="commonRules.notNullRule">
              <el-select v-model="formData.storehouseId" filterable placeholder="请选择">
                <el-option v-for="it in merchants" :key="it.supplyCode" :label="it.merchantName" :value="it.supplyCode"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="仓库:" prop="merchantId" :rules="commonRules.notNullRule">
              <el-select v-model="formData.merchantId" filterable placeholder="请选择">
                <el-option v-for="it in merchants" :key="it.ckdm" :label="it.merchantName" :value="it.supplyCode"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="运费模板:" prop="freightTemplateId" :rules="commonRules.notNullRule">
              <el-select v-model="formData.freightTemplateId" filterable placeholder="请选择">
                <el-option v-for="it in freightList" :key="it.id" :label="it.name" :value="it.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签:">
              <span v-if="formData.goodsTags && formData.goodsTags.length">{{formData.goodsTags}}</span>
              <span v-else>暂无</span>
            </el-form-item>
            <el-form-item label="是否上架:" prop="upShelf" :rules="commonRules.notNullRule">
              <el-switch v-model="formData.upShelf" :active-value="1" :inactive-value="0"></el-switch>
            </el-form-item>
            <el-form-item label="是否售卖:" prop="onSale">
              <el-radio-group v-model="formData.onSale">
                <el-radio :label="1">是,立即售卖</el-radio>
                <el-radio :label="2">否,定时售卖</el-radio>
                <el-radio :label="3">仅上架,不售卖</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="formData.onSale === 2" label="开售时间:" prop="onSaleTime">
              <el-date-picker value-format="timestamp" v-model="formData.onSaleTime" type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="是否允许搜索:" prop="canSearch">
              <el-switch :active-value="1" :inactive-value="0" v-model="formData.canSearch"></el-switch>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品描述" name="desc">
          <el-form :model="formData" ref="descForm" label-width="120px"   :disabled="!isEdit">
            <el-form-item label="商品主图:" prop="mainPic" :rules="commonRules.notNullRule">
              <!-- <MyUpload v-model="formData.mainPic" /> -->
              <el-upload
                class="avatar-uploader"
                :action="upladUrl"
                 name="file"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="uploadMainPicSuccess"
              >
                <img v-if="formData.mainPic" :src="formData.mainPic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="列表封面图:" prop="coverPic" :rules="commonRules.notNullRule">
             <el-upload
                class="avatar-uploader"
                :action="upladUrl"
                 name="file"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="uploadCoverPicSuccess"
              >
                <img v-if="formData.coverPic" :src="formData.coverPic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="商品图:" prop="picSet" :rules="commonRules.notNullRule">
              <!-- <MyUpload v-model="formData.picSet" :limit='5' /> -->
              <ul class="list-pic">
                <li v-if="formData.picSet && formData.picSet.length > 0">
                  <div class="pic-item" v-for="(item,index) in formData.picSet" :key="item">
                    <img :src="item" alt="" />
                    <i class="el-icon-delete" v-if="isEdit" @click="delPicSet(index)"></i>
                  </div>
                </li>
                <li v-if="!formData.picSet || formData.picSet.length < 5">
                  <el-upload
                    class="avatar-uploader"
                    :action="upladUrl"
                    :multiple="true"
                    name="file"
                    :show-file-list="false"
                    :before-upload="beforeUpload"
                    :on-success="uploadPicSetSuccess"
                  >
                    <i  class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </li>
              </ul>
            </el-form-item>
            <el-form-item label="商品详情" :rules="commonRules.notNullRule">
              <tinymce :height="360" v-model="formData.description"></tinymce>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="attr">
          <el-form :model="formData" ref="attrForm" label-width="120px"   :disabled="!isEdit">
            <el-form-item label="属性组:" prop="backCatName" :rules="commonRules.notNullRule">
              <span>{{formData.backCatName}}</span>
              <el-button type="primary" size="mini" @click="chooseProp">选择属性组</el-button>
            </el-form-item>
            <el-form-item label="自定义规格:" :rules="commonRules.notNullRule">
              <div class="specificaiton">
                <div v-for="it in currentChildrenCat" :key="it.id">
                  <template v-if="it.inputType === 0">
                    <div class="specificaiton_title">{{it.name}}</div>
                    <div class="cat_input" v-for="(cat, idx) in it.inputs" :key="idx">
                      <el-input style="width:100px;margin:0 10px" size='mini' v-model="it.inputs[idx]" />
                      <span class="error" v-if="isEdit" @click="deleteCat(it,idx)">×</span>
                    </div>
                    <!-- 这个新增按钮并不会在属性组中新增子属性，但当对应规格明细列表选择新增属性的时候，再次进来详情要从规格明细列表中遍历取出属性组没有的属性 -->
                    <el-button type="primary" size="mini" @click="addCat(it)" style="margin-left: 10px;">新增</el-button>
                  </template>
                  <template v-else>
                    <div class="specificaiton_title">{{it.name}}</div>
                    <el-tag style="margin:0 10px" v-for="(cat, idx) in it.inputs" :key="idx">{{cat}}</el-tag>
                  </template>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="规格明细:" v-if="formData.goodsSkuList&&formData.goodsSkuList.length > 0">
              <!-- <specifications :goodsSkuList.sync="formData.goodsSkuList" :catArr="currentChildrenCat"/> -->
               <div class="pl_text">
                <span class="title">批量设置</span>
                <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(0)">市场价</button>
                <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(1)">碧选价</button>
                <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(2)">最高佣金</button>
                <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(3)">上架</button>
                <button :disabled="multipleSelection.length === 0" class="txt" @click.prevent="showBatch(4)">图片</button>
              </div>
              <el-table v-loading="listLoading" element-loading-text="给我一点时间" border :data="formData.goodsSkuList" @selection-change="handleSelectionChange"
                highlight-current-row style="width: 100%">
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column label="图片" width="160px">
                  <template slot-scope="scope">
                    <el-upload
                      class="avatar-uploader"
                      :action="upladUrl"
                      name="file"
                      :show-file-list="false"
                      :before-upload="beforeUpload"
                      :on-success="uploadSkuPicSuccess"
                    >
                      <div @click="getUploadIndex(scope.$index)">
                      <img v-if="scope.row.picSet" :src="scope.row.picSet" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                      </div>
                    </el-upload>
                  </template>
                </el-table-column>
                <el-table-column prop="skuId" label="SKU码">
                </el-table-column>
                <el-table-column prop="erpColorValue" label="ERP颜色">
                </el-table-column>
                <el-table-column prop="erpSizeValue" label="ERP规格">
                </el-table-column>
                <el-table-column v-for="(it, idx) in currentChildrenCat" :key="idx" :label="it.name" :prop="it.name">
                </el-table-column>

                <el-table-column prop="price" label="市场价格" width="120px">
                  <template slot-scope="scope">
                    <!-- <el-input type="text" v-model="scope.row.price" style="width: 100%" @blur="changeVal($event, scope.row)"></el-input>
                    <div class="el-form-item__error" style="top: 60%;display: none"></div> -->
                    <el-form-item :prop="'goodsSkuList['+scope.$index+'].price'" :rules="commonRules.priceRule" style="margin: 30px 0">
                      <el-input type="text" v-model="scope.row.price" style="width: 100%" ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="lanPrice" label="碧选价" width="120px">
                  <template slot-scope="scope">
                    <!-- <el-input type="text" v-model="scope.row.lanPrice" style="width: 100%" @blur="changeVal($event, scope.row)"></el-input>
                    <div class="el-form-item__error" style="top: 60%;display: none"></div> -->
                    <el-form-item :prop="'goodsSkuList['+scope.$index+'].lanPrice'" :rules="commonRules.priceRule" style="margin: 30px 0">
                      <el-input type="text" v-model="scope.row.lanPrice" style="width: 100%" @blur="changeVal($event, scope.row)"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="maxCommission" label="最高佣金" width="120px">
                  <template slot-scope="scope">
                      <!-- <el-input type="text" v-model="scope.row.maxCommission" style="width: 100%" @blur="changeVal($event, scope.row)"></el-input>
                      <div class="el-form-item__error" style="top: 60%;display: none"></div> -->
                      <el-form-item :prop="'goodsSkuList['+scope.$index+'].maxCommission'" :rules="commonRules.priceRule" style="margin: 30px 0">
                        <el-input type="text" v-model="scope.row.maxCommission" style="width: 100%" @blur="changeVal($event, scope.row)"></el-input>
                      </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="regionPrice" label="大区价">
                </el-table-column>
                <el-table-column prop="directorPrice" label="董事价">
                </el-table-column>
                <el-table-column prop="remainStock" label="库存">
                </el-table-column>
                <el-table-column prop="hasSale" label="已售">
                </el-table-column>
                <el-table-column prop="upShelf" label="是否上架" width="160px">
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.upShelf" active-text="上架" inactive-text="下架" :active-value="1" :inactive-value="0">
                    </el-switch>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="操作" fixed="right" width="130px">
                  <template slot-scope='{row, $index}'>
                    <el-button @click="bindCat(row, $index)">关联规格</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <!-- <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog> -->
      <div class="btn-box" v-show="isEdit">
        <div>
          <el-button class="filter-item"  v-if="isEdit" type="success" size="small" @click="save">保存</el-button>
          <el-button class="filter-item" v-else @click="updateUpshelf" type="danger" size="small">下架</el-button>
        </div>
      </div>
      <el-dialog title="选择属性组" :visible.sync="catDialogVisible">
        <el-table border :data="catList" highlight-current-row @current-change="handleCurrentChange" style="width: 100%">
          <el-table-column prop="name" label="当前选择">
            <template slot-scope="scope">
              <label class="input-radio">
                <input type="radio" :value="scope.row" v-model="currentCat" />
                <span></span>
              </label>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="属性组名称"></el-table-column>
          <el-table-column prop="description" label="属性组描述"></el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="catDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="getCurrentCat">确 定</el-button>
        </span>
      </el-dialog>
       <el-dialog title="关联规格" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
        <el-form ref="form" label-width="100px">
          <el-form-item label="ERP规格：">
            <el-input :readonly="true" :value="currentSpecErpSizeId" />
          </el-form-item>
          <!-- <el-form-item label="已选SKU:">
            <div class="el-tag-box">
              <el-tag v-for="(item, index) of haveChosen" :key="index" :closable="true" @close="delItem(index)">{{item.name}}</el-tag>
            </div>
          </el-form-item> -->
          <el-form-item label="关联SKU:" style="margin-top:20px">
            <!-- <el-select v-model="currentSpecOption" multiple placeholder="请选择">
              <el-option-group v-for="(group, idx) in options" :key="idx" :label="group.label">
                <el-option v-for="(item, idx2) in group.children" @click.native="handleChangeSku(group.label,item, idx)" :disabled="item.disabled"
                  :key="idx2" :label="item.label" :value="item.value">
                </el-option>
              </el-option-group>
            </el-select> -->
             <m-cascader :hasChoice="hasChoice" :options="options" @getValue="handleChangeSku" :newValue="currentSpecOption" ref="mCascader"/>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetParams('sku')">取 消</el-button>
          <el-button type="primary" @click="chooseCat">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="批量操作" :visible.sync="batchVisible" width="40%">
        <template v-if="batchType === 0">
          <span>市场价：</span>
          <el-input style="width:200px" placeholder="请输入市场价格" v-model="batchVal" />
        </template>
        <template v-if="batchType === 1">
          <span>碧选价：</span>
          <el-input style="width:200px" placeholder="请输入碧选价" v-model="batchVal" />
        </template>
        <template v-if="batchType === 2">
          <span>最高佣金：</span>
          <el-input style="width:200px" placeholder="请输入最高佣金" v-model="batchVal" />
        </template>
        <template v-if="batchType === 3">
          <span>上架：</span>
          <el-switch v-model="batchVal" active-text="上架" inactive-text="下架" :active-value="1" :inactive-value="0">
          </el-switch>
        </template>
        <template v-if="batchType === 4">
          <span>上传图片：</span>
           <el-upload
              class="avatar-uploader"
              :action="upladUrl"
                name="file"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="uploadbatchValSuccess"
            >
              <img v-if="batchVal" :src="batchVal" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </template>
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetParams">取 消</el-button>
          <el-button type="primary" @click="submitBatch">确 定</el-button>
        </span>
      </el-dialog>
    </section>
  </div>
</template>
<script>
import {
  getGoodsDetail,
  getBrandList,
  updateGoods,
  getCatBindAttr,
  getAttr,
  updateUpSelfStatus
} from '@/api/goodMiddleStage'
import  mCascader  from './components/mCascader'
import { getMerchantWarehouse } from '@/api/common'
import { getAllList } from '@/api/freight' // 运费模板
import Tinymce from '@/components/Tinymce'
// import MyUpload from '@/components/Upload/myUpload'
export default {
  components: {
    Tinymce,
    mCascader
    // MyUpload
  },
  data() {
    return {
      isEdit: true,
      activeTab: 'base',
      brands: [], // 品牌列表
      merchants: [], // 供应商、仓库列表
      freightList: [], // 运费模板列表
      catList: [], // 商品绑定属性组
      catDialogVisible: false,
      // dialogVisible: false,
      // dialogImageUrl: '',
      currentCat: {}, // 当前选择属性组
      currentChildrenCat: [],
      formData: {},

      listLoading: false,
      dialogVisible: false,
      batchVisible: false, // 批量操作弹框
      batchVal: '', // 批量操作的值
      batchType: '', // 当前批量操作的类型  0 市场加 1 碧选价格 2最高佣金 3 上下架 4 图片
      currnetIdx: 0, //当前操作行
      options: [], // 关联规格级联选择框数据源
      multipleSelection: [], // 批量选择
      currentSpecErpSizeId: '', // 当前规格ERPid
      currentSpecOption: [], // 当前关联规格值
      hasChoice: false
    }
  },
  created() {
    this.fetchData() // 获取商品详情
    this.fetchBindAttrData() // 获取商品绑定属性组
  },
  methods: {
    // 获取商品详情
    fetchData() {
      getGoodsDetail({
        goodsId: this.$route.query.goodsId
      }).then(res => {
        this.formData = res.data
        this.fetchBrandData() // 获取品牌
        this.fetchMerchantData() // 获取供应商、仓库列表
        this.fetchFreightData() // 获取运费模板列表
        this.isEdit = res.data && (res.data.upShelf === 0)
        this.formData.goodsSkuList = this.formData.goodsSkuList.map(it => {
          let { attrInfo } = it
          if (attrInfo) {
            attrInfo.forEach(val => {
              it[val.attrName] = val.attrValue
            })
          } else {
            it.attrInfo = []
          }
          return it
        })
        if (this.formData.freightTemplateId) {
          this.formData.freightTemplateId = this.formData.freightTemplateId + ''
        }
        // 当前已经绑定了子属性 查询子属性信息 带出相关属性和属性值
        if (this.formData.goodsAttrGroupId) {
          // 生成子属性
          this.getCurrentCat()
        }
      }).catch(e => {
        console.log(e)
      })
    },
    // 获取品牌
    fetchBrandData() {
      getBrandList().then(res => {
        if (res.data && res.data.data) {
           this.brands = res.data.data
           if (this.formData.brandId){
              const index = this.brands.findIndex(i => i.id === this.formData.brandId)
              if (index === -1){
                this.formData.brandId = ''
              }
           }
        }
      }).catch(e => {
        console.log(e)
        this.brands = []
      })
    },
    // 获取供应商、仓库列表
    fetchMerchantData() {
      getMerchantWarehouse().then(res => {
        if(res.data && res.data.viewList){
          const { viewList } = res.data
          this.merchants = viewList.filter(item => item.supplyCode !== null)
          if (this.formData.storehouseId){
            const index = this.merchants.findIndex(i => i.supplyCode === this.formData.storehouseId)
            if (index === -1){
              this.formData.storehouseId = ''
            }
          }
          if (this.formData.merchantId){
            const index = this.merchants.findIndex(i => i.supplyCode === this.formData.merchantId)
            if (index === -1){
              this.formData.merchantId = ''
            }
          }
        }
      }).catch(e => {
        console.log(e)
        this.merchants = []
      })
    },
    // 获取运费模板列表
    fetchFreightData() {
      getAllList().then(res => {
        if(res){
          this.freightList = res.data || []
          if (this.formData.freightTemplateId){
            const index = this.freightList.findIndex(i => i.id === this.formData.freightTemplateId)
            if (index === -1){
              this.formData.freightTemplateId = ''
            }
          }
        }
      }).catch(e => {
        console.log(e)
        this.freightList = []
      })
    },
    // 获取商品绑定属性组
    fetchBindAttrData() {
      getCatBindAttr({
        backCatId: this.$route.query.backCatId
      }).then(res => {
        if(res && res.data){
          this.catList = res.data.goodsAttrGroupList || []
        }
      }).catch(e => {
        console.log(e)
        this.catList = []
      })
    },
    // 选择属性组
    chooseProp() {
      this.catDialogVisible = true
      if (this.catList.length === 0) {
        this.fetchBindAttrData()
      }
    },
    handleCurrentChange(val) {
      this.currentCat = val
    },
    // 保存
    save() {
      this.$refs['baseForm'].validate((valid1) => {
        this.$refs['descForm'].validate((valid2) => {
          this.$refs['attrForm'].validate((valid3) => {
              console.log(this.formData)
              //商品名称
              const checkName = [
                {key: 'name', message: '商品标题不能为空'},
                {key: 'subName', message: '商品副标题不能为空'},
                {key: 'businessModel', message: '经营模式不能为空'},
                {key: 'storehouseId', message: '供应商不能为空'},
                {key: 'merchantId', message: '仓库不能为空'},
                {key: 'freightTemplateId', message: '运费模板不能为空'},
                {key: 'mainPic', message: '商品主图不能为空'},
                {key: 'coverPic', message: '列表封面不能为空'},
                {key: 'picSet', message: '商品图不能为空'},
                {key: 'description', message: '商品详情不能为空'}
              ]
              for(let i=0; i< checkName.length;i++){
                const keyName = checkName[i].key
                if (this.formData[keyName] === null || this.formData[keyName] === undefined || this.formData[keyName]===''){
                  this.$message.error(checkName[i].message)
                  return
                }
              }
              if (this.currentChildrenCat.length <= 0) {
                this.$message.error('请选择商品属性自定义规则')
                return
              }

              if (this.formData.brandId){
                const index = this.brands.findIndex(i => i.id === this.formData.brandId)
                if (index === -1){
                   this.$message.error('商品品牌已变更，请重新选择')
                   return
                }
              }

              if (this.formData.storehouseId){
                const index = this.merchants.findIndex(i => i.supplyCode === this.formData.storehouseId)
                if (index === -1){
                  this.$message.error('仓库已变更，请重新选择')
                  return
                }
              }
              if (this.formData.merchantId){
                const index = this.merchants.findIndex(i => i.supplyCode === this.formData.merchantId)
                if (index === -1){
                  this.$message.error('供应商已变更，请重新选择')
                   return
                }
              }
              if (this.formData.freightTemplateId){
                const index = this.freightList.findIndex(i => i.id === this.formData.freightTemplateId)
                if (index === -1){
                  this.$message.error('运费模板已变更，请重新选择')
                  return
                }
              }

              const goodsSkuList = this.formData.goodsSkuList
              let msg = ''
              for(let i=0;i<goodsSkuList.length;i++){

                if (goodsSkuList[i].picSet == undefined ||goodsSkuList[i].picSet.length <= 0) {
                  msg = 'sku码【'+goodsSkuList[i].skuId + '】的图片不能为空'
                  break
                }
                if ( goodsSkuList[i].price == undefined || goodsSkuList[i].price === '') {
                  msg = 'sku码【'+goodsSkuList[i].skuId + '】的市场价不能为空'
                  break
                }
                 if ( goodsSkuList[i].price < 0 ) {
                  msg = 'sku码【'+goodsSkuList[i].skuId + '】的市场价不得小于零'
                  break
                }
                if (goodsSkuList[i].lanPrice == undefined ||goodsSkuList[i].lanPrice === '') {
                  msg = 'sku码【'+goodsSkuList[i].skuId + '】的碧选价不能为空'
                  break
                }
                if (goodsSkuList[i].lanPrice < 0 ) {
                  msg = 'sku码【'+goodsSkuList[i].skuId + '】的碧选价不得小于零'
                  break
                }
                if (goodsSkuList[i].maxCommission == undefined ||goodsSkuList[i].maxCommission === '') {
                  msg = 'sku码【'+goodsSkuList[i].skuId + '】的最高佣金不能为空'
                  break
                }
                if (goodsSkuList[i].maxCommission < 0  ) {
                  msg = 'sku码【'+goodsSkuList[i].skuId + '】的最高佣金不得小于零'
                  break
                }
                if ((goodsSkuList[i].lanPrice - goodsSkuList[i].maxCommission * 0.8 )< 0){
                   msg = 'sku码【'+goodsSkuList[i].skuId + '】的碧选价不得小于最高佣金的80%'
                   break
                }
                if (!goodsSkuList[i].attrInfo) {
                  msg = 'sku码【'+goodsSkuList[i].skuId + '】的规格未关联'
                  break
                }
                if ( goodsSkuList[i].attrInfo.length !== this.currentChildrenCat.length) {
                  msg = '自定义规格已变更，请重新关联规格'
                  break
                }
                let hasNotWrite = false
                if (goodsSkuList[i].attrInfo.length > 0) {
                  for(let j=0;j<goodsSkuList[i].attrInfo.length;j++){
                    if (goodsSkuList[i].attrInfo[j].attrValue === '') {
                      hasNotWrite = true
                      msg = 'sku码【'+goodsSkuList[i].skuId + '】的关联规格【'+goodsSkuList[i].attrInfo[j].attrName+'】值不能为空'
                      break
                    }
                  }
                }
                if (this.currentChildrenCat.length !== goodsSkuList[i].attrInfo.length) {
                  msg = '自定义规格已变更，请重新关联规格'
                  break
                }
                let hasChangeName = false
                for(let j=0;j<this.currentChildrenCat.length;j++){
                  const index = goodsSkuList[i].attrInfo.findIndex(g => g.attrName === this.currentChildrenCat[j].name)
                  if (index === -1){
                    hasChangeName = true
                    msg = '自定义规格已变更，请重新关联规格'
                    break
                  }
                  const index1 = goodsSkuList[i].attrInfo.findIndex(g => this.currentChildrenCat[j].inputs.includes(g.attrValue))
                  if (index1 === -1) {
                    hasChangeName = true
                    msg = '自定义规格已变更，请重新关联规格'
                    break
                  }
                  if (hasChangeName) {
                    break
                  }
                }
                if (hasNotWrite || hasChangeName) {
                  break
                }
              }
              if(msg){
                this.$message.error(msg)
                return
              }
              if (valid1 && valid2 && valid3) {
                const newGoodsSkuList = []
                this.formData.goodsSkuList.forEach(item  => {
                  newGoodsSkuList.push({
                    attrInfo: item.attrInfo,
                    directorPrice: item.directorPrice,
                    lanPrice: item.lanPrice,
                    maxCommission: item.maxCommission,
                    picSet: item.picSet,
                    price: item.price,
                    regionPrice: item.regionPrice,
                    skuId: item.skuId,
                    upShelf: item.upShelf
                  })
                })
                const data = {
                  alias: this.formData.alias || '',
                  // attrSearchIndex: '',
                  baseSaleVolume: this.formData.baseSaleVolume,
                  brandId: this.formData.brandId,
                  businessModel: this.formData.businessModel,
                  canSearch: this.formData.canSearch,
                  coverPic: this.formData.coverPic,
                  description: this.formData.description,
                  // flag: '',
                  freightTemplateId: this.formData.freightTemplateId,
                  goodsAttrGroupId:this.formData.goodsAttrGroupId,
                  goodsId:this.formData.goodsId,
                  goodsSkuList: newGoodsSkuList,
                  introduction:this.formData.introduction || '',
                  mainPic: this.formData.mainPic,
                  merchantId: this.formData.merchantId,
                  name: this.formData.name,
                  onSale: this.formData.onSale,
                  onSaleTime:this.formData.onSaleTime || '',
                  goodsType: this.formData.goodsType || '',
                  picSet: this.formData.picSet,
                  price: this.formData.price || '',
                  saleVolume: this.formData.saleVolume,
                  sort: this.formData.sort || '',
                  storehouseId: this.formData.storehouseId,
                  story: this.formData.story || '',
                  subName: this.formData.subName,
                  upShelf: this.formData.upShelf
                }
                if (this.saveing) return
                this.saveing = true
                updateGoods(data).then(res => {
                  this.$message.success('操作成功')
                  this.fetchData()
                  console.log('保存信息', data)
                  this.saveing = false
                }).catch(e => {
                  this.$message.error('操作失败')
                  console.log(e)
                  this.saveing = false
                })
              }
            })
        })
      })

    },
    // 获取当前所选属性
    getCurrentCat() {
      if (this.currentCat.id) {
        this.formData.goodsAttrGroupId = this.currentCat.id
      }
      if (!this.formData.goodsAttrGroupId) {
        return this.$message.error('请选择属性')
      }
      getAttr({
        attrGroupId: this.formData.goodsAttrGroupId
      }).then(res => {
        if (res&&res.data) {
          const { goodsSkuList } = this.formData
          this.currentChildrenCat = res.data.attrList.map(it => {
            if (!it.inputs) {
              it.inputs = []
            }
            /*
              生成规格明细自定义属性项。
              说明：列表所带来的自定义属性值在属性组的子属性中可能不存在，因此要遍历出不存在的自定义值加入到当前子属性组
            */
            goodsSkuList.forEach(arr => {
              let { attrInfo } = arr
              if (attrInfo && attrInfo.length > 0) {
                attrInfo.forEach(val => {
                  // 判断是否有相同属性， 子属性组不存在该值就新增该值
                  if (it.name === val.attrName &&!it.inputs.includes(val.attrValue)) {
                    it.inputs.push(val.attrValue)
                  }
                })
              }
            })
            return it
          })
          this.catDialogVisible = false
        }
      }).catch(e => {
        console.log(e)
        this.currentChildrenCat = []
      })
    },
     // 手动输入新增
    addCat(val) {
      val.inputs.push('')
    },
     // 手动输入属性 删除
    deleteCat(val, idx) {
      val.inputs && val.inputs.splice(idx, 1)
    },
    //商品上下架
    updateUpshelf() {
      updateUpSelfStatus({
        goodsId: this.formData.goodsId,
        upShelf: Number(!this.formData.upShelf)
      }).then(res => {
        this.$message.success('操作成功')
        this.fetchData()
      }).catch(e => {
        console.log(e)
      })
    },
    // =======规格明细相关
    //批量选择
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 展示批量操作弹框
    showBatch(val) {
      this.batchVisible = true
      this.batchType = val
    },
    // 规格批量操作
    submitBatch() {
      this.listLoading = true
      const keys = ['price', 'lanPrice', 'maxCommission', 'upShelf', 'picSet']
      if (this.batchType < 3){
        const rex = /^[0-9]+(\.\d+)?$/
        if (!rex.test(this.batchVal)){
          this.$message.error("价格只能是大于等于零")
          return
        }
      }
      this.multipleSelection.forEach(item => {
        const index = this.formData.goodsSkuList.findIndex(i => i.id === item.id)
        if (index  >= 0) {
          if (keys[this.batchType] === 'picSet') {
            this.fromOther = true
            this.$set(this.formData.goodsSkuList[index], 'picSet', [this.batchVal])
          } else {
            this.$set(this.formData.goodsSkuList[index], [keys[this.batchType]], this.batchVal)
            this.setPrice(index)
          }
        }
      })
      this.batchVal = ''
      this.batchVisible = false
       this.listLoading = false
    },
    // 关联规格弹窗确认
    chooseCat() {
      const option = this.currentSpecOption
      if (!option) {
        this.$message.error('请选择关联规格')
        return
      }
      if (option.length < this.currentChildrenCat.length) {
        this.$message.error('还剩'+ (this.currentChildrenCat.length-option.length )+'项未关联规格')
        return
      }
      // 判断是否选择过
      if (this.hasChoiceSku()) {
        this.$message.error('关联规格重复，请重新选择')
        return
      }
      this.currentChildrenCat.forEach(item => {
        if (this.formData.goodsSkuList[this.currnetIdx][item.name]) {
          delete this.formData.goodsSkuList[this.currnetIdx][item.name]
        }
      })
      this.formData.goodsSkuList[this.currnetIdx].attrInfo = []
      option.forEach(it => {
        const [prop, value] = it.value.split(':') // 取出级联选择器的值， 第一位为表格属性 第二位为表格值
        this.$set(this.formData.goodsSkuList[this.currnetIdx], prop, value)// 赋值sku操作
        // attrInfo 自定义属性集合
        // let id = this.formData.goodsSkuList[this.currnetIdx].id
        const index = this.currentChildrenCat.findIndex(i => i.name === prop)
        let id = this.currentChildrenCat[index].id
        this.formData.goodsSkuList[this.currnetIdx].attrInfo.push({
          attrId: id,
          attrName: prop,
          attrValue: value,
          isPicAttr: 0
        })
      })
      this.$refs.mCascader.closeShowChoice()
      this.currentSpecOption = []
      this.dialogVisible = false

    },
    // 生成已选择tag
    generateHaveChose(idx) {
      this.currentSpecOption = []
      let arr = []
      let val = this.formData.goodsSkuList[idx]
      this.options.forEach(it => {
        if (val[it.label]) {
          const index = it.children.findIndex(i => i.label === val[it.label])
          arr.push({
           value: `${it.label}:${val[it.label]}`,
           key: it.value + '' + (index !== -1 ? it.children[index].value : '')
          })
        }
      })
      this.currentSpecOption = arr
    },
    // 关联规格按钮
    bindCat(val, idx) {
      if(this.currentChildrenCat.length <= 0) {
        return this.$message.error('请先选择属性组')
      }
      this.currnetIdx = idx // 记录当前操作索引
      let hasCatIsNull = this.checkCatNoNull()
      if (hasCatIsNull) {
        return this.$message.error('请填写完整自定义属性')
      }
      this.generateCat() // 生成级联选择器数据源
      this.generateHaveChose(idx) // 生成关联规格

      this.currentSpecErpSizeId = '颜色:' + val.erpColorValue + ";尺码:" + val.erpSizeValue
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.mCascader.initData()
      })
    },
    // 检查自定义属性是否有空的， 有空的要添加属性，一般针对手动输入的属性
    checkCatNoNull() {
      for (let val of this.currentChildrenCat) {
        if (val.inputs.length === 0) {
          return true
        }
        // 手动输入属性框 不能有值为空
        for (let b of val.inputs) {
          if (!b) {
            return true
          }
        }
      }
      return false
    },
    // 生成关联规格弹窗-级联选择器数据源
    generateCat() {
      this.options = []
      this.currentChildrenCat.forEach(item => {
        const skuArr = {
          value: item.id,
          label: item.name,
          children: []
        }
        item.inputs.forEach((i, index) => {
          skuArr.children.push({
            value: index,
            label: i
          })
        })
        this.options.push(skuArr)
      })

    },
    // 判断是否选择过
    // 判断是否选择过
    hasChoiceSku() {
      let hasChoice = false
      for(let i=0;i<this.formData.goodsSkuList.length;i++){
        if (this.formData.goodsSkuList[i].attrInfo && i !== this.currnetIdx && this.formData.goodsSkuList[i].attrInfo.length > 0) {
          let hasNum = 0
          this.formData.goodsSkuList[i].attrInfo.forEach(item => {
            const val = item.attrName + ':' + item.attrValue
            const index = this.currentSpecOption.findIndex(i => i.value === val)
            if (index !== -1) {hasNum += 1}
          })
          if (hasNum === this.formData.goodsSkuList[i].attrInfo.length) {
            hasChoice = true
          }
        }
      }
      return hasChoice
    },
    // 关联sku规格发生变化-数据出
    // handleChangeSku(prop, val, idx) {
    handleChangeSku(data) {
      if (data.index === 1){
        this.currentSpecOption = [...data.value]
      }
      this.hasChoice = this.hasChoiceSku()
    },
    // 关联sku规格弹窗及批量添加取消回调
    resetParams(type) {
      if (type === 'sku'){
        this.$refs.mCascader.closeShowChoice()
      }
      this.dialogVisible = false
      this.currentSpecOption = []
      this.batchVisible = false
      this.batchVal = ''
    },
     // 碧选价和最高佣金输入失去焦点回调
    changeVal(e, row) {
      const index = this.formData.goodsSkuList.findIndex(i => i.id === row.id)
      if (index !== -1) {
        this.setPrice(index)
      }
    },
    // 设置大区和董事价
    setPrice(index) {
      if (this.formData.goodsSkuList[index].lanPrice && this.formData.goodsSkuList[index].maxCommission){
        this.$set(this.formData.goodsSkuList[index], 'regionPrice', (this.formData.goodsSkuList[index].lanPrice  - this.formData.goodsSkuList[index].maxCommission * 0.5).toFixed(2) )
        this.$set(this.formData.goodsSkuList[index], 'directorPrice', (this.formData.goodsSkuList[index].lanPrice  - this.formData.goodsSkuList[index].maxCommission * 0.8).toFixed(2) )
        // 大区  大区价=碧选价 - 最高佣金*50%
        // 董事  董事价=碧选价 - 最高佣金*80%
      }
    },
    beforeUpload(file){
      const isImage = file.type.split('/')[0] === 'image'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error('请上传正确图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    // 图片上传成功回调
    uploadMainPicSuccess(res) {
      this.$set(this.formData, 'mainPic', res.filePath)
    },
    uploadCoverPicSuccess(res){
      this.$set(this.formData, 'coverPic', res.filePath)
    },
    uploadbatchValSuccess(res){
      this.batchVal = res.filePath
    },
    uploadPicSetSuccess(res) {
      if (!this.formData.picSet) {
        this.$set(this.formData, 'picSet', [res.filePath])
      } else if (this.formData.picSet.length < 5) {
        this.formData.picSet.push(res.filePath)
      }
    },
    delPicSet(index) {
      this.formData.picSet.splice(index, 1)
    },
    uploadSkuPicSuccess(res){
      this.$set(this.formData.goodsSkuList[this.goodsSkuIndex], 'picSet', [res.filePath])
    },
    getUploadIndex(index){
      this.goodsSkuIndex = index
    }
  }
}
</script>
<style lang="scss" scoped>
.goods-detail{
  .btn-box {
    padding: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    margin-bottom: 10px;
  }
  .mask_container {
    position: relative;
    width: 100%;
    height: 100%;
  }
  .mask {
    position: absolute;
    z-index: 99;
    top: 40px;
    left: 0;
    width: 100%;
    height: 95%;
    background: rgba($color: #000000, $alpha: 0.1);
  }
  .cat_input {
    position: relative;
    display: inline-block;
    margin-bottom: 10px;
    .error {
      cursor: pointer;
      position: absolute;
      top: 0px;
      right: 7px;
      display: inline-block;
      width: 20px;
      height: 20px;
      background: red;
      z-index: 98;
      line-height: 20px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      font-size: 22px;
    }
  }
  .specificaiton {
    width: 60%;
    border: 1px solid #d4cbcb;
  }
  .specificaiton_title{
    background: #F2F2F2;
    padding-left: 20px;
  }
}
.pl_text {
  display: flex;
  .title {
    font-size: 14px;
    font-weight: 600;
    margin-right: 10px;
  }
  .txt {
    background: #fff;
    border: none;
    cursor: pointer;
    margin-right: 10px;
  }
}
.avatar-uploader {
  width: 148px;
  height: 148px;
  /deep/ .el-upload {
    width: 100%;
    height: 100%;
    line-height: 148px;
  }
  .avatar {
    width: 100%;
    height: 100%;
  }
}
.list-pic {
  overflow: hidden;
  li {
    float: left;
    position: relative;
    overflow: hidden;
  }
  .pic-item {
    width: 148px;
    height: 148px;
    font-size: 0;
    margin-right: 10px;
    border: 1px dashed #eee;
    border-radius: 6px;
    position: relative;
    float:left;
    img {
      width: 148px;
      height: 148px;
    }
    .el-icon-delete {
      position: absolute;
      top: 0;
      right: 0;
      font-size: 18px;
      color: red;
      cursor: pointer;
    }
  }
}

</style>
